<?php
namespace App\Http\Controllers;
use App\Pay\ItpPay;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class PayController extends Controller
{   
    public function toPay($totalMoney,$orderid,$type,$notifyUrl="http://www.eaifx.net/notify"){ //弹出支付宝或者微信的收钱二维码
        $payChannelId =  $type== 1 ? '6000000003' : '6000000002'; //6000000003:支付宝扫码支付,6000000002:微信
        $itppay_config['appid']  = getenv('PayAppId');
        $itppay_config['key'] = getenv('PayAppKey');

        //获取客户端IP
        $user_IP = isset($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
        $user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];

        /* 请求参数，参数须按字符升序排列*/
        $parameter=array(
                "amount"         =>"$totalMoney",//[必填]订单总金额，单位(分)
                "appid"          =>$itppay_config['appid'],//[必填]//交易发起所属app
                "body"           =>"毅思科技服务费",//[必填]商品描述
                "clientIp"       =>"$user_IP",//[必填]客户端IP
                "cpChannel"      =>"",//CP分发渠道
                "currency"       =>"",//币种，默认RMB
                "description"    =>"",//订单附加描述
                "expireMs"       =>"",//过期时间毫秒数，默认24小时过期
                "extra"          =>"",//附加数据，以键值对形式存放，例如{"key":"value"}
                "mchntOrderNo"   =>$orderid,//[必填]商户订单号，必须唯一性
                "notifyUrl"      =>$notifyUrl,//[必填]订单支付结果异步通知地址，用于接收订单支付结果通知，必须以http或https开头
                "returnUrl"      =>"http://www.eaifx.net/paysuccess",//[必填]订单支付结果同步跳转地址，用于同步跳转到商户页面，必须以http或https开头
                "subject"        =>"毅思（北京）科技有限责任公司",//[必填]商品名称
                "version"        =>"pc_NoEncrypt",//接口版本号，值为pc_NoEncrypt时,则明天平台返回商户参数时，不进行RSA加密
                "payChannelId"   =>"$payChannelId"//支付渠道id
        );
        /* *
        * 建立请求
        */
        $itpPay = new ItpPay($itppay_config);
        $url = $itpPay->itppay_gateway;
        $orderInfo=$itpPay->getOrderInfo($parameter);
//        $html=$itpPay->RequestForm($orderInfo,'正在跳转到支付页面...');
//        echo $html;
        
        $data = array("orderInfo" => $orderInfo);                                                                      
        $ch = curl_init($url);   
        curl_setopt($ch, CURLOPT_POST, 1);    
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  
        $result = curl_exec($ch);
        curl_close($ch);
        $qrcode = json_decode($result);
        return $qrcode;
    }
    
    //订单支付结果异步通知地址，用于接收订单支付结果通知
    public function notify(){
        @header("Content-Type:text/html; charset=utf-8");
        $status = '';
        /* *
        * 获取传递数据
        */
         
        $data = file_get_contents("php://input");
        Storage::append('payvps.log',$data);
        $parameter = json_decode($data, true);
        $signature = $parameter["signature"];
        unset($parameter["signature"]);

       /* *
        * 签名
        */
       $itppay_config['appid']  = getenv('PayAppId');
       $itppay_config['key'] = getenv('PayAppKey');
    
       $itpPay = new ItpPay($itppay_config);
       $signature_local = $itpPay->setSignature($parameter);
       if($signature && $signature == $signature_local){
	
            //$parameter["orderNo"]明天云平台生成的订单号
            //$parameter["mchntOrderNo"]商户订单号，可根据商户订单号查询商户网站中该订单信息，并执行业务处理
            //$parameter["orderDt"]下单日期
            //$parameter["paidTime"]订单支付完成时间
            //$parameter["extra"]附加数据
            //$parameter["paySt"]支付结果状态，0:待支付；1:支付中；2:支付成功；3:支付失败；4:已关闭
//            Storage::append('pay.log', 'paySt----'.$parameter["paySt"]);
            switch($parameter["paySt"]){
		case 0:
                    $status = 0;
                    Storage::append('pay.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->待支付\r\n");
                    Storage::append('pay2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->待支付\r\n");
                    break;
		case 1:
                    $status = 1;
                    Storage::append('pay.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付中\r\n");
                    Storage::append('pay2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付中\r\n");
                    break;
		case 2:
                   $status = 2;
                    Storage::append('pay.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付成功\r\n");
                    Storage::append('pay2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付成功\r\n");
                    break;
		case 3:
                    $status = 3;
                    Storage::append('pay.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付失败\r\n");
                    Storage::append('pay2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付失败\r\n");
                    break;
		case 4:
                    $status = 4;
                    Storage::append('pay.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->已关闭\r\n");
                    Storage::append('pay2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->已关闭\r\n");
                    break;
            }
	
            foreach($parameter as $k=>$v){
                    Storage::append('pay.log', $k."=".$v."\r\n");
                    Storage::append('pay2.log', $k."=".$v."\r\n");
            }
            Storage::append('pay.log',"\r\n\r\n");
            Storage::append('pay2.log',"\r\n\r\n");
        }else{
            $status = -1;
            Storage::append('pay.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->验签失败\r\n");
            Storage::append('pay2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->验签失败\r\n");
        }
        
        //Storage::append('pay.log', '状态'.$status);
        //DB::connection()->enableQueryLog();
        $pdata['status'] = $status;
        $pdata['ptime']  = time();
        $pdata['acturepay']  = $parameter["amount"];
        if($status == 2){ //支付成功修改用户会员到期时间
            $buyinfo    = DB::table('waihui_pay_log')->where('order_num',$parameter["mchntOrderNo"])->select('buy_month','userid')->first();
            if($buyinfo){ //信息正确
                $expiretime = strtotime("+".$buyinfo->buy_month." month"); //支付购买月份到期时间
                $pdata['expiretime']  = $expiretime;
                $duration   = $expiretime - strtotime('now'); //购买时长
                $userinfo   = DB::table('waihui_member')->where('id',$buyinfo->userid)->select('expire_time','applytime','expire_time','hasapply')->first();
                $tiyanday   = getenv('tiyan');//体验天数 变量
                if((($userinfo->expire_time - $userinfo->applytime)/86400 <= $tiyanday) && ($userinfo->hasapply == 1)){ //判断是不是体验时间
                    $mdata['expire_time'] = $expiretime; //现在为体验账户时间则从购买时间开始计算
                }else{
                    $mdata['expire_time'] = $userinfo->expire_time?($userinfo->expire_time + $duration):$expiretime;//如果原先有到期时间，则新的到期时间为原到期时间加上本次购买时长；如果原先没有购买过，则本次到期时间即为$expiretime。
                }
                $mdata['isvip'] = '1';
                DB::table('waihui_member')->where('id',$buyinfo->userid)->update($mdata); //修改用户会员到期时间
            }
        }
        $res = DB::table('waihui_pay_log')->where('order_num',$parameter["mchntOrderNo"])->update($pdata);
        
        //DB::table('waihui_pay_log'); 
        //$queries = DB::getQueryLog(); 
        //Storage::append('pay.log', $queries);
        if($res){
            echo "{\"success\":\"true\"}";  //此处不可以修改
            exit;
        }else{
            echo "{\"success\":\"false\"}";
            exit;
        }
//        echo "{\"success\":\"true\"}";
//        exit;
    }
    //支付
    public function pay(Request $request){
        $email = '';
        $id = $request->session()->get('eai')['id'];
        if(isset($id) && $id){
            $email = DB::table('waihui_member')->where('id',$id)->value('email');
        }
        return view('pay.pay',compact('email'));
    }
    // 支付的第二页面
    public function paytwo(Request $request){
        $session = $request->session()->get('eai');
        if(!$session){
            return redirect('login'); //未登录 去登录页
        }
        $isYh          = intval(trim($request->a)); //是不是优惠了
        $buyMonth      = intval(trim($request->yhMonth)); //购买几个月
        if(!$buyMonth){
            return redirect('pay'); //未选择购买信息 去选择产品
        }
        $isBuyVps      = intval(trim($request->isbuyvps)); //是不是购买了vps
        $pirect        = $isYh == 1 ? 2499 : 2999; //每个月的价格
        $buyVpsMoney   = $isBuyVps == 1 ? ($buyMonth*200) : 0; //购买vps的总金额
        $cpMoney       = $buyMonth == 12 ? (12*$pirect) : ($buyMonth*$pirect); //购买插件的总金额
        $totalMoney    = $buyVpsMoney + $cpMoney;//需要付款的总金额
        $allMoney      = $buyVpsMoney + ($buyMonth*2999);//没有优惠的总金额
        $yhMoney       = $allMoney-$totalMoney;//优惠的总金额
       
        return view('pay.pay_next',compact('buyVpsMoney','cpMoney','totalMoney','allMoney','yhMoney','buyMonth','isBuyVps','isYh','buyorderid'));
    }
    //提交产品
    public function addPay(Request $request){
        $sessiondata   = $request->session()->get('eai');
        if(!$sessiondata){
            return json_encode(array('status'=>0,'msg'=>'用户未登录'));
        }
        $khName        = trim($request->khName); //收货人姓名
        $khTel         = trim($request->khTel);//收货人手机号
        $khProvince    = trim($request->khProvince);//收货人省
        $khCity        = trim($request->khCity);//收货人市
        $khCountry     = trim($request->khCountry);//收货人区
        $khDetails     = trim($request->khDetails);//收货人详细地址
        if($khName == '' || $khTel == '' || $khProvince == '' || $khCity == '' || $khCountry == '' || $khDetails == ''){
            return json_encode(array('status'=>4,'msg'=>'请输入正确的收货地址'));
        }
        $isYh          = intval(trim($request->isYH)); //是不是优惠了
        $buyMonth      = intval(trim($request->yhMonth)); //购买几个月
        if(!$buyMonth){
            return json_encode(array('status'=>1,'msg'=>'请选择购买的类型'));
        }
        $isBuyVps      = intval(trim($request->isbuyvps)); //是不是购买了vps
        $pirect        = $isYh == 1 ? 2499 : 2999; //每个月的价格
        $vps_pre_money = 200; //vps每个月的价格
        $buyVpsMoney   = $isBuyVps == 1 ? ($buyMonth*$vps_pre_money) : 0; //购买vps的总金额
        $cpMoney       = $buyMonth == 12 ? (12*$pirect) : ($buyMonth*$pirect); //购买插件的总金额
        $totalMoney    = $buyVpsMoney + $cpMoney;//付款总金额
        $allMoney      = $buyVpsMoney + ($buyMonth*2999);//没有优惠的总金额
        $yhMoney       = $allMoney-$totalMoney;//优惠的总金额
        $buyorderid    = GetBuyOrderId();//获取唯一订单号
        $type          = trim($request->type);//付款方式
        //入库数据
        $mysqldata = array(
                        'userid'    =>$sessiondata['id'],
                        'order_num' =>$buyorderid,
                        'buy_month' =>$buyMonth,
//                        'status'    =>1,
                        'is_buy_vps'=>$isBuyVps,
                        'is_yh'      =>$isYh,
                        'money'      =>$totalMoney,
                        'yhmoney'   =>$yhMoney,
                        'order_time'=>time(),
                        'username'  =>$khName,
                        'tel'        => $khTel,
                        'province'   => $khProvince,
                        'city'        => $khCity,
                        'country'     => $khCountry,
                        'addressinfo' =>$khDetails,
                        'vps_per_price'=>$vps_pre_money,
                        'paytype'       =>$type
                    );
        $qrcode = $this->toPay($totalMoney*100,$buyorderid,$type);
        if(isset($qrcode->QRCode)){
            $id = DB::table('waihui_pay_log')->insertGetId($mysqldata);//获取到支付二维码以后入库
            if($id){
                return json_encode(array('status'=>2,'msg'=>'提交成功','qrcode'=>$qrcode->QRCode,'orderid'=>$buyorderid));
            }else{
                return json_encode(array('status'=>3,'msg'=>'提交失败'));
            }
        }else{
            return json_encode(array('status'=>5,'msg'=>'获取支付信息失败'));
        }
    }
    
    // 支付成功
    public function paysuccess(Request $request){
        $sessionData = $request->session()->get('eai');
        
        if(!$sessionData){
            return redirect('/login');
        }
        $orderid = trim($request->orderid);
        if($orderid == '0'){ //错误
            $status = 0;
        }else{
            $status = 1;
            $data   = DB::table('waihui_pay_log')->select('status','username','tel','province','city','country','addressinfo')->where([['order_num','=',$orderid],['userid','=',$sessionData['id']]])->first();
        }
        return view('pay.paysuccess',compact('status','data'));
    }
    
    public function checkPayResult(Request $request){
        $sessionData = $request->session()->get('eai');
        if(!$sessionData){
            return json_encode(array('type'=>-2)); //没有登录
        }
        $orderid = trim($request->get('orderid')) ? trim($request->get('orderid')) : '';
        $type = trim($request->get('type')) ? trim($request->get('type')) : '';
        if($orderid == '' || !$orderid){
            return json_encode(array('type'=>-2)); //数据有误
        }
        if($type == 1){ //1代表单独购买VPS
            $data = DB::table('waihui_only_vps')->where([['orderid','=',"$orderid"],['userid','=',$sessionData['id']]])->first();
        }else{
            $data = DB::table('waihui_pay_log')->where([['order_num','=',"$orderid"],['userid','=',$sessionData['id']]])->first();
        }
        if(!$data){
            return json_encode(array('type'=>-2)); //没有此数据
        }else{
            return json_encode(array('type'=>1,'status'=>$data->status));
        }
        
    }
    
    //单独购买vps
    public function payVps(Request $request){
        $sessiondata   = $request->session()->get('eai');
        if(!$sessiondata){
            return json_encode(array('status'=>0,'msg'=>'用户未登录'));
        }
        $month = trim($request->get('month'));
        $money = trim($request->get('money'));
        $email = trim($request->get('email'));
        $paytype = trim($request->get('ddtype'));
        if(!$month){
            return json_encode(array('status'=>1,'msg'=>'请选择购买的月份'));
        }
        
        if(!$email){
            return json_encode(array('status'=>2,'msg'=>'请填写正确的邮箱'));
        }
        $actureMoney = $month==3 ? 600 : ($month==6 ? 1200 : 2400);
        if($money != $actureMoney){
            return json_encode(array('status'=>3,'msg'=>'请正确操作'));
        }
        $orderid    = GetBuyOrderId();//获取唯一订单号
        $insertData = array(
                           'userid'=>$sessiondata['id'],
                           'orderid'=>$orderid,
                           'month'=>$month,
                           'money'=>$actureMoney,
                           'paytype'=>$paytype,
                           'order_time'=>time(),
                           'email'=>$email
                      );
        $notifyUrl = 'http://www.eaifx.net/notifyvps';
        $qrcode = $this->toPay($actureMoney*100,$orderid,$paytype,$notifyUrl);
        if(isset($qrcode->QRCode)){
            $id = DB::table('waihui_only_vps')->insertGetId($insertData);//获取到支付二维码以后入库
            if($id){
                return json_encode(array('status'=>2,'msg'=>'提交成功','qrcode'=>$qrcode->QRCode,'orderid'=>$orderid));
            }else{
                return json_encode(array('status'=>3,'msg'=>'提交失败'));
            }
        }else{
            return json_encode(array('status'=>5,'msg'=>'获取支付信息失败'));
        }
    }
    
    //vps支付异步通知地址
    public function notifyVps(){
        @header("Content-Type:text/html; charset=utf-8");
        $status = '';
        /* *
        * 获取传递数据
        */
        $data = file_get_contents("php://input");
        Storage::append('payvps.log',$data);
        $parameter = json_decode($data, true);
        $signature = $parameter["signature"];
        unset($parameter["signature"]);

       /* *
        * 签名
        */
       $itppay_config['appid']  = getenv('PayAppId');
       $itppay_config['key'] = getenv('PayAppKey');
    
       $itpPay = new ItpPay($itppay_config);
       $signature_local = $itpPay->setSignature($parameter);
       if($signature && $signature == $signature_local){
	
            //$parameter["orderNo"]明天云平台生成的订单号
            //$parameter["mchntOrderNo"]商户订单号，可根据商户订单号查询商户网站中该订单信息，并执行业务处理
            //$parameter["orderDt"]下单日期
            //$parameter["paidTime"]订单支付完成时间
            //$parameter["extra"]附加数据
            //$parameter["paySt"]支付结果状态，0:待支付；1:支付中；2:支付成功；3:支付失败；4:已关闭
//            Storage::append('pay.log', 'paySt----'.$parameter["paySt"]);
            switch($parameter["paySt"]){
		case 0:
                    $status = 0;
                    Storage::append('payvps.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->待支付\r\n");
                    Storage::append('payvps2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->待支付\r\n");
                    break;
		case 1:
                    $status = 1;
                    Storage::append('payvps.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付中\r\n");
                    Storage::append('payvps2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付中\r\n");
                    break;
		case 2:
                   $status = 2;
                    Storage::append('payvps.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付成功\r\n");
                    Storage::append('payvps2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付成功\r\n");
                    break;
		case 3:
                    $status = 3;
                    Storage::append('payvps.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付失败\r\n");
                    Storage::append('payvps2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->支付失败\r\n");
                    break;
		case 4:
                    $status = 4;
                    Storage::append('payvps.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->已关闭\r\n");
                    Storage::append('payvps2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->已关闭\r\n");
                    break;
            }
	
            foreach($parameter as $k=>$v){
                    Storage::append('payvps.log', $k."=".$v."\r\n");
                    Storage::append('payvps2.log', $k."=".$v."\r\n");
            }
            Storage::append('payvps.log',"\r\n\r\n");
            Storage::append('payvps2.log',"\r\n\r\n");
        }else{
            $status = -1;
            Storage::append('payvps.log', date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->验签失败\r\n");
            Storage::append('payvps2.log',date("Y-m-d H:i:s",time())."---[".$parameter["mchntOrderNo"]."]--->验签失败\r\n");
        }
        
        //Storage::append('pay.log', '状态'.$status);
        //DB::connection()->enableQueryLog();
        $pdata['status'] = $status;
        $pdata['ptime']  = time();
        $pdata['acturepay']  = $parameter["amount"]; //此处没有除以100，单位是分
//        Storage::append('payvps.log','money:'.$parameter["amount"]);
        if($status == 2){ //支付成功修改用户的邮箱
            $userinfo    = DB::table('waihui_only_vps')->select('userid','email')->where('orderid',$parameter["mchntOrderNo"])->first();
            if($userinfo){
                DB::table('waihui_member')->where('id',$userinfo->userid)->update(['email'=>$userinfo->email]);
            }
        }
        $res = DB::table('waihui_only_vps')->where('orderid',$parameter["mchntOrderNo"])->update($pdata);
        
        //DB::table('waihui_pay_log'); 
        //$queries = DB::getQueryLog(); 
        //Storage::append('pay.log', $queries);
        if($res){
            echo "{\"success\":\"true\"}";  //此处不可以修改
            exit;
        }else{
            echo "{\"success\":\"false\"}";
            exit;
        }
//        echo "{\"success\":\"true\"}";
//        exit;
    }
}
